package dao.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;


import utils.DbUtil;

import dao.DatabaseDao;
import entity.Database;
import entity.TableInfo;
import entity.Tables;

public class DatabaseDaoImpl implements DatabaseDao {

	private String database = "jrbac";
	
	public List<Database> getList() throws SQLException {
		ArrayList<Database> list = new ArrayList<Database>();
		List<Tables> tables = DbUtil.queryRunner().query("show tables from "+database, new BeanListHandler<Tables>(Tables.class));
		for(Tables t : tables) {
			System.out.println(t.getTables_in_jrbac());
			TableInfo tableInfo = DbUtil.queryRunner().query("show table status from "+database+" like '"+t.getTables_in_jrbac()+"'", new BeanHandler<TableInfo>(TableInfo.class));
			System.out.println(tableInfo);
			Database datab = new Database();
			System.out.println(tableInfo.getName());
			datab.setName(tableInfo.getName());
			datab.setRows(tableInfo.getRows());
			datab.setSize(Math.round(tableInfo.getData_length()/1024/1024));
			datab.setIndex(Math.round(tableInfo.getIndex_length()/1024/1024));
			datab.setTsize(datab.getSize() + datab.getIndex());
			datab.setAuto(tableInfo.getAuto_increment());
			datab.setUpdate_time(tableInfo.getUpdate_time());
			datab.setNote(tableInfo.getComment());
			datab.setChip(tableInfo.getData_free());
			System.out.println(datab);
			list.add(datab);
		}
		return list;
	}

	public int getListCount() {
		
		return 0;
	}

	public int doRepair(String table) throws SQLException {
		Connection conn = DbUtil.getConnect();
		Statement stmt = conn.createStatement();
		stmt.execute("REPAIR  TABLE " + table);
		stmt.close();
		return 1;
		//return DbUtil.queryRunner().update("REPAIR TABLE "+table, table);
	}

	public int doOptimize(String table) throws SQLException {
		Connection conn = DbUtil.getConnect();
		Statement stmt = conn.createStatement();
		stmt.execute("OPTIMIZE  TABLE " + table);
		stmt.close();
		return 1;
	}

	public List<Tables> getAllTable() throws SQLException {
		return DbUtil.queryRunner().query("show tables from "+database, new BeanListHandler<Tables>(Tables.class));
	}
}
